"""
波动率突破策略(backtrader实现)
策略逻辑：
1. 计算ATR波动率指标
2. 当价格突破前日收盘价±ATR×倍数时交易
3. 尾盘平仓(日内策略)
"""

import backtrader as bt

class VolatilityBreakoutStrategy(bt.Strategy):
    params = (
        ('atr_period', 14),  # ATR计算周期
        ('atr_multiplier', 1.5),  # AR倍数
        ('exit_time', 15),  # 平仓时间(小时)
    )

    def __init__(self):
        # 计算ATR
        self.atr = bt.indicators.ATR(self.data, period=self.p.atr_period)
        
        # 记录前日收盘价
        self.prev_close = None

    def next(self):
        # 更新前日收盘价(每日开盘时)
        if self.data.datetime.time().hour == 9 and self.data.datetime.time().minute == 30:
            self.prev_close = self.data.close[-1]
            
        if self.prev_close is None:
            return
            
        # 计算突破阈值
        upper_band = self.prev_close + self.atr[0] * self.p.atr_multiplier
        lower_band = self.prev_close - self.atr[0] * self.p.atr_multiplier
        
        # 交易信号
        if not self.position:
            if self.data.high[0] >= upper_band:
                self.buy()  # 向上突破买入
            elif self.data.low[0] <= lower_band:
                self.sell()  # 向下突破卖出
                
        # 尾盘平仓
        if self.position and self.data.datetime.time().hour >= self.p.exit_time:
            self.close()

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(VolatilityBreakoutStrategy)
    # 这里添加数据和其他配置
    cerebro.run()